﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lamps_Studio.Models;
using System.Web.Security;
using Lamps_Studio.DataAccessLayer;

namespace Lamps_Studio.Controllers
{
    public class AccountController : Controller
    {
        DataAccesHelper dbHelper = new DataAccesHelper();

        [HttpGet]
        public ActionResult Login()
        {
            bool Ok = Request.IsAuthenticated;
            if (Request.IsAuthenticated)
            {
                return RedirectToAction("Index","Home");
            }
            else return View();
        }

        [HttpPost]
        public ActionResult Login(LoginFormModel form)
        {
            if (ModelState.IsValid)
            {
                bool validAccount = dbHelper.checkLogin(form.Username, form.Password);

                if (validAccount)
                {
                    FormsAuthentication.SetAuthCookie(form.Username, form.RememberMe);
                    bool Ok = Request.IsAuthenticated;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Cannot login. Check your username and password");
                    return View(form);
                }
            }
            return View(form);
        }


        [HttpGet]
        public ActionResult Register()
        {
            bool Ok = Request.IsAuthenticated;
            if (Request.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterFormModel form)
        {
            if (ModelState.IsValid)
            {
                string validAccount = dbHelper.getCurrentDisplayName(form.Username);

                if (validAccount != null)
                {
                    ModelState.AddModelError("", "User's account exists ! Choose another username !");
                    return View(form);
                }
                else
                {
                   //Add new user here

                }
            }
            return View(form);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }


    }
}
